package com.wyhello.tube4.spring.controller;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.wyhello.tube4.pojo.Dictionary;
import com.wyhello.tube4.pojo.Draw;
import com.wyhello.tube4.pojo.Position;
import com.wyhello.tube4.pojo.Reside;
import com.wyhello.tube4.pojo.Tube;
import com.wyhello.tube4.spring.model.ResideRecordsModel;
import com.wyhello.tube4.util.PinyinConv;
@Controller
public class ResideRecordsController {
	@Autowired
	private ResideRecordsModel resideRecordsModel;
	/**
	 * 添加受热面前查询锅炉信息
	 * 查询锅炉的信息
	 * @param reside
	 * @return
	 */
	@RequestMapping("/reside/queryReside")
	public ModelAndView queryReside(Reside reside){
			List<Reside> boilers =  resideRecordsModel.queryResideByBoiler();
			ModelAndView model = new ModelAndView("surfaceAddBatched","boilers",boilers);
			return model;
	}
	/**
	 * 添加管排前查询锅炉信息（批量添加管排页面）
	 * @param reside
	 * @return
	 */
	@RequestMapping("/reside/queryResideRow")
	public ModelAndView queryResideRow(){
			List<Reside> boilers =  resideRecordsModel.queryResideByBoiler();
			ModelAndView model = new ModelAndView("rowAddBatched","boilers",boilers);
			return model;
	}
	/**
	 * 用ajax查询对应锅炉的受热面
	 * @param parent 父id
	 * @param response
	 */
	@RequestMapping("/reside/surface")
	public void queryjson(int parentid,HttpServletResponse response){
		Reside reside = resideRecordsModel.getResideById(parentid);
		Set<Reside> surfaces = reside.getResides();
		Map<Integer,String> map = new TreeMap<Integer,String>();
		for (Reside surface : surfaces) {
			map.put(surface.getId(), surface.getName());
		}
		JSONObject json = JSONObject.fromObject(map);
		PrintWriter out = null;
		try {
			response.setCharacterEncoding("UTF-8");
			out = response.getWriter();
		} catch (IOException e) {
			e.printStackTrace();
		}
		out.print(json);
	}
	
	@RequestMapping("/reside/updateResideImg")
	public String updateResideImg(
			@RequestParam(value = "file1", required = false) MultipartFile file1, 
			@RequestParam(value = "file2", required = false) MultipartFile file2, 
			Reside reside,String uri,HttpServletRequest request){
		
		Reside r = resideRecordsModel.getResideById(reside.getId());
		r.setName(reside.getName());
		if(reside.getLevel()!=2){
			r.setBoilerNum(reside.getBoilerNum());
		}
		
		String path = request.getSession().getServletContext().getRealPath("upload"); 
		
		//如果修改时没有上传图片，则可能之前已经上传过，不要删除原来的图片
		if(!"".equals(file1.getOriginalFilename())){
			String assignImagePath =  System.currentTimeMillis() + file1.getOriginalFilename();
			r.setAssignImagePath(assignImagePath);
			File fileAssignImagePath = new File(path, assignImagePath);  
	        if(!fileAssignImagePath.exists()){  
	        	fileAssignImagePath.mkdirs();  
	        }
	        try {  
	        	file1.transferTo(fileAssignImagePath);  
	        } catch (Exception e) {  
	            e.printStackTrace();  
	        }  
		}
		
		if(!"".equals(file2.getOriginalFilename())){
			String descImagePath = System.currentTimeMillis() + file2.getOriginalFilename();
			r.setDescImagePath(descImagePath);
	        File fileDescImagePath = new File(path, descImagePath);  
	        if(!fileDescImagePath.exists()){  
	        	fileDescImagePath.mkdirs();  
	        }
	        try {  
	        	file2.transferTo(fileDescImagePath);  
	        } catch (Exception e) {  
	            e.printStackTrace();  
	        }  
		}
		
		resideRecordsModel.updateReside(r);
		return uri;
	}
	
	/**
	 * 删除reside图片
	 * @param file,request,model
	 * @return
	 */
	@RequestMapping("/reside/delResideImg")  
	public void delResideImg(HttpServletRequest request, HttpServletResponse response){
		String id = request.getParameter("id");
		Reside r = resideRecordsModel.getResideById(Integer.parseInt(id));
		String imgae = request.getParameter("image");
		
		String filename = "";
		if("assign".equals(imgae)){
			filename = r.getAssignImagePath();
			r.setAssignImagePath(null);
		}
		
		if("desc".equals(imgae)){
			filename = r.getDescImagePath();
			r.setDescImagePath(null);
		}
		
		resideRecordsModel.updateReside(r);
		
		String path = request.getSession().getServletContext().getRealPath("upload"); 
		File file = new File(path, filename);  
		file.delete();
		
		try {
			response.sendRedirect(request.getHeader("referer"));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 保存Reside信息及修改
	 * @param reside
	 * @return
	 */
	@RequestMapping("/reside/save")
	public String saveReside(Reside reside,int parentId,String uri){
		if(reside.getId()==0){
			if(parentId!=0){
				Reside r = resideRecordsModel.getResideById(parentId);
				reside.setReside(r);
				resideRecordsModel.saveReside(reside);
			}else{
				resideRecordsModel.saveReside(reside);
			}
			
		}else{
			if(parentId!=0){
				Reside surface = resideRecordsModel.getResideById(reside.getId());
				surface.setName(reside.getName());
				if(surface.getLevel()!=2){
					surface.setBoilerNum(reside.getBoilerNum());
				}
				resideRecordsModel.updateReside(surface);
			}else{
				resideRecordsModel.updateReside(reside);
			}
		}
		
		return uri;
	}
	/**
	 * 查询所有的受热面 不分锅炉
	 * @return
	 */
	@RequestMapping("/reside/reside")
	public ModelAndView query(){
		List<Reside> resides =  resideRecordsModel.queryResideByBoiler();
		ModelAndView model = new ModelAndView("main");
		model.addObject("resides", resides);
		return model;
	}
	/**
	 * 查询对应受热面的管排
	 * @param reside
	 * @return
	 */
	@RequestMapping("/reside/queryrow")
	public ModelAndView queryrow(int parentId){
		//Reside reside = resideRecordsModel.getResideById(parentId);
		//Set<Reside> rows =  reside.getResides();
		List<Reside> rows =  resideRecordsModel.queryResideByParendID(parentId);
		ModelAndView model = new ModelAndView("list");
		model.addObject("rows",rows);
		return model;
	}
	/**
	 * 根据id查询信息
	 * @param id
	 * @return
	 */
	@RequestMapping("/reside/updateResideGet")
	public ModelAndView getResideById(int id,String url){
		Reside reside = resideRecordsModel.getResideById(id);
		ModelAndView model = new ModelAndView(url,"reside",reside);
		return model;
	}
	/**
	 * 删除归属信息
	 * @param request
	 * @return
	 */
	@RequestMapping("/reside/deletereside")
	public String delete(HttpServletRequest request){
		String ids = request.getParameter("deletid");
		Reside r = resideRecordsModel.getResideById(Integer.parseInt(ids));
		//r.getResides().clear();
		//resideRecordsModel.deleteReside("("+ids+")"); 
		resideRecordsModel.deleteOj(r);
		return "rowSuccess";
	}
	
	/**
	 * 受热面批量添加
	 * @param parentId
	 * @param count
	 * @return
	 */
	@RequestMapping("/reside/surfaceSaveBatched")
	public String surfaceSaveBatched(int parentId, String surfaceNames){
		
		Reside parentReside = resideRecordsModel.getResideById(parentId);
		String[] names = surfaceNames.split("\r\n");
		Reside surface = null;
		for (int i = 0; i < names.length; i++) {
			surface = new Reside();
			surface.setReside(parentReside);
			surface.setName(names[i].trim());
			surface.setLevel(2);
			resideRecordsModel.saveReside(surface);
		}
		
		return "surfaceSuccess";
	
	}
	
	/**
	 * 管排批量添加
	 * @param parentId
	 * @param count
	 * @return
	 */
	@RequestMapping("/reside/rowsSaveBatched")
	public String rowsSaveBatched(int parentId, int count){
		
		Reside parentReside = resideRecordsModel.getResideById(parentId);
		int size = parentReside.getResides().size();
		//int size1 = resideRecordsModel.queryCountOfChildrenByParentId(parentId);
		Reside row = null;
		for (int i = size + 1; i <= count + size; i++) {
			row = new Reside();
			row.setReside(parentReside);
			StringBuffer sb = new StringBuffer();
			sb.append(parentReside.getName()).append("第").append(i).append("排");
			row.setName(sb.toString());
			row.setLevel(3);
			
			String cot;
			if(i<10){
				cot = "00"+i;
			}else if(i<100){
				cot = "0"+i;
			}else{
				cot = String.valueOf(i);
			}
			
			row.setBoilerNum(cot);
			
			resideRecordsModel.saveReside(row);
		}
		
		return "rowSuccess";
	
	}
	
	/**
	 * 管的信息极修改
	 * @param tube
	 * @return
	 */
	@RequestMapping("/reside/updateTube")
	public String updateTube(Tube tube){
			Tube t = resideRecordsModel.getTubeById(tube.getId());
			t.setName(tube.getName());
			t.setNumber(tube.getNumber());
			resideRecordsModel.updateTube(t);                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                
		return "tubeSuccess1";
	}
	
	@RequestMapping("/reside/saveTube")
	public String saveTube(int resideId,int count){
			int size = resideRecordsModel.queryCountTubeByResideId(resideId);
			
			Tube tube = null;
			for(int i=size+1; i<=count+size;i++){
				tube = new Tube();
				tube.setReside(resideRecordsModel.getResideById(resideId));
				StringBuffer sb = new StringBuffer(50);
				//sb.append(tube.getReside().getReside().getName()).append(tube.getReside().getName()).append("第").append(i).append("根");
				sb.append(tube.getReside().getName()).append("第").append(i).append("根");
				tube.setName(sb.toString());
				sb.setLength(0);
				String ss=PinyinConv.cn2py(tube.getReside().getReside().getName());
				if(ss.indexOf("、")!=-1){
					ss = ss.substring(ss.indexOf("、")+1,ss.indexOf("、")+4);
				}else{
					ss = ss.substring(0,3);
				}
				String cot;
				if(i<10){
					cot = "00"+i;
				}else if(i<100){
					cot = "0"+i;
				}else{
					cot = String.valueOf(i);
				}
				
				sb.append(tube.getReside().getReside().getReside().getBoilerNum()).append(ss.toUpperCase()).append(tube.getReside().getBoilerNum()).append(cot);
				tube.setNumber(sb.toString());
				resideRecordsModel.saveTube(tube);
			}
		return "tubeSuccess";
	}
	/**
	 * 根据管ID查询管信息
	 * @param id
	 * @param uil
	 * @return
	 */
	@RequestMapping("/reside/getTubeById")
	public ModelAndView getTubeById(int id,String url){
		Tube tube = resideRecordsModel.getTubeById(id);
		ModelAndView model = new ModelAndView(url,"tube",tube);
		return model;
	}
	/**
	 * 删除管信息
	 * @param id
	 * @return
	 */
	@RequestMapping("/reside/deleteTube")
	public String deleteTube(String id){
		Tube tube = resideRecordsModel.getTubeById(Integer.parseInt(id));
		resideRecordsModel.deleteTOj(tube);
		//resideRecordsModel.deleteTube("("+ids+")");
		return "positionSuccess";
	}
	/**
	 * 批量删除管信息
	 * @param ids
	 * @return
	 */
	@RequestMapping("/reside/deleteTubes")
	public String deleteTubes(String ids){
		//System.out.println(ids);
		String[] id = ids.split(",");
		for (int i = 0; i < id.length; i++) {
			Tube tube = resideRecordsModel.getTubeById(Integer.parseInt(id[i]));
			resideRecordsModel.deleteTOj(tube);
		}
		return "tubeSuccess2";
	}
	
	@RequestMapping("/reside/ajaxTube")
	public void ajaxTube(int parentid,HttpServletResponse response){
		Reside reside = resideRecordsModel.getResideById(parentid);
		Set<Tube> tubes = reside.getTubes();
		Map<Integer,String> map = new TreeMap<Integer,String>();
		for (Tube tube : tubes) {
			map.put(tube.getId(), tube.getName());
		}
		JSONObject json = JSONObject.fromObject(map);
		PrintWriter out = null;
		try {
			response.setCharacterEncoding("UTF-8");
			out = response.getWriter();
		} catch (IOException e) {
			e.printStackTrace();
		}
		out.print(json);
	}
	/**
	 * 查询所有的锅炉
	 * @param url 执行之后跳转的路径
	 * @return
	 */
	@RequestMapping("/reside/boilers")
	public ModelAndView tubeboilers(String url){
		List<Reside> boilers =  resideRecordsModel.queryResideByBoiler();
		ModelAndView model = new ModelAndView(url,"boilers",boilers);
		return model;
	}
	/**
	 * 对选中管进行添加位置信息
	 * @param manage
	 * @return
	 */
	@RequestMapping("/reside/addPosition")
	public ModelAndView addPosition(String manage){
		ModelAndView model = new ModelAndView("addPosition","ids",manage);
		List<Dictionary> dictionarys = resideRecordsModel.queryDictionaryByType();
		List<Dictionary> dictionaryWeld = resideRecordsModel.queryDictionaryByWeld();
		List<Dictionary> dictionaryWire = resideRecordsModel.queryDictionaryByWire();
		model.addObject("dictionarys", dictionarys);
		model.addObject("dictionaryWeld", dictionaryWeld);
		model.addObject("dictionaryWire", dictionaryWire);
		return model;
	}
	/**
	 * 保存位置信息
	 * @param position
	 * @param parentId
	 * @return
	 */
	@RequestMapping("/reside/savePosition")
	public String savePosition(Position position, String ids){
			String[] str = ids.split(",");
			Position p = null;
			for(int i = 0; i < str.length; i++){
				try {
					p = (Position) position.clone();
				} catch (CloneNotSupportedException e) {
					e.printStackTrace();
				}
				p.setTube(resideRecordsModel.getTubeById(Integer.valueOf(str[i])));
				resideRecordsModel.savePosition(p);
			}
		return "positionSuccess";
	}
	/**
	 * 修改位置信息
	 * @param position
	 * @return
	 */
	@RequestMapping("/reside/updatePosition")
	public String updatePosition(Position position){
		Position p = resideRecordsModel.getPositionById(position.getId());
		p.setPositionName(position.getPositionName());
		p.setStuff(position.getStuff());
		p.setOuterDiameter(position.getOuterDiameter());
		p.setWallThick(position.getWallThick());
		p.setSolder(position.getSolder());
		p.setHeat(position.isHeat());
		p.setUsing(position.isUsing());
		//外径预警参数理论上限值
		p.setOutLimitValue(position.getCreepLimitValue());
		//外径预警参数预警值
		p.setOutWarnValue(position.getCreepWarnValue());
		//相对蠕胀预警参数理论上限值
		p.setCreepLimitValue(position.getCreepLimitValue());
		//相对蠕胀预警参数预警值
		p.setCreepWarnValue(position.getCreepWarnValue());
		//壁厚预警参数理论下限值
		p.setWallLimitValue(position.getWallLimitValue());
		//壁厚预警参数预警值
		p.setWallWarnValue(position.getWallWarnValue());
		//磨损速率预警参数
		p.setSpeedValue(position.getSpeedValue());
		//估算寿命预警参数
		p.setLifeValue(position.getLifeValue());
		resideRecordsModel.updatePosition(p);
		return "positionSuccess1";
	}
	/**
	 * 查询单个位置信息
	 * @param id
	 * @return
	 */
	@RequestMapping("/reside/getPositionById")
	public ModelAndView getPositionById(int id){
		Position position = resideRecordsModel.getPositionById(id);
		ModelAndView model = new ModelAndView("addPosition1","position",position);
		return model;
	}
	/**
	 * 单个删除位置信息
	 * @param id
	 * @return
	 */
	@RequestMapping("/reside/deletePosition")
	public String deletePosition(String id){
		Position position = resideRecordsModel.getPositionById(Integer.parseInt(id));
		resideRecordsModel.deletePOj(position);
		return "positionSuccess";
	}
	@RequestMapping("/reside/uploading")
	public ModelAndView uploading(String id){
		ModelAndView model = new ModelAndView("uploading","ids",id);
		/*List<Dictionary> dictionarys = resideRecordsModel.queryDictionaryByType();
		model.addObject("dictionarys", dictionarys);*/
		return model;
	}
	/**
	 * 图片上传
	 * @param file,request,model
	 * @return
	 */
	 @RequestMapping("/reside/upload")  
	    public String upload(@RequestParam(value = "file", required = false) MultipartFile file, HttpServletRequest request, Model model,String tubeId) {   
			//System.out.println(tubeId);
			String[] tube = tubeId.split(",");
			String path = request.getSession().getServletContext().getRealPath("upload"); 
	        
			//2013-10-12重命名文件
			String oFileName = System.currentTimeMillis() + file.getOriginalFilename(); 
	        int beginIndex = oFileName.lastIndexOf(".");
	        String extention = "";
	        if(beginIndex != -1){
	        	extention = oFileName.substring(beginIndex);
	        }
	        String fileName = System.currentTimeMillis() + "_" + Math.random() + extention; 
	        
			File files = new File(path, fileName);  
	        if(!files.exists()){  
	            files.mkdirs();  
	        }
	        try {  
	            file.transferTo(files);  
	        } catch (Exception e) {  
	            e.printStackTrace();  
	        }  
	        model.addAttribute("filesrc", request.getContextPath()+"/upload/"+fileName); 
	        Draw draw = new Draw();
	        draw.setName(fileName);
	        draw.setDescription("upload");
	        Tube tubeo = null;
	        for(int i=0;i<tube.length;i++){
	        	tubeo = resideRecordsModel.getTubeById(Integer.parseInt(tube[i]));
	        	draw.getTubes().add(tubeo);
	        	resideRecordsModel.saveDraw(draw);
	        	
	        	//2013-10-11保存管记录的图片id字段
	        	//System.out.println("========================" + draw.getId());
	        	tubeo.setDraw(draw);
	        	resideRecordsModel.updateTube(tubeo);
	        }
	        return "success";
	    }
	@RequestMapping("/reside/getDrawById")
	public ModelAndView getDrawById(HttpServletRequest request,String id){
		Draw draw = resideRecordsModel.getDrawById(Integer.parseInt(id));
		ModelAndView model = new ModelAndView("draw","draw",draw);
		return model;
	}
	/**
	 * 图片删除
	 * @param file,request,model
	 * @return
	 */
	@RequestMapping("/reside/delDraw")  
	public void delDraw(HttpServletRequest request, HttpServletResponse response){
		String id = request.getParameter("tubeId");
		Tube tube = resideRecordsModel.getTubeById(Integer.parseInt(id));
		//图片不能被删除，因为可能同时被其他管引用
		tube.setDraw(null);
		resideRecordsModel.updateTube(tube);
		try {
			response.sendRedirect(request.getHeader("referer"));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	/*@RequestMapping("/ceshi")
	public void ceshi(HttpServletRequest request,HttpServletResponse response,Draw draw){
		System.out.println(draw.getName()+draw.getDescription());
		try {
			response.sendRedirect(request.getHeader("referer"));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}*/
}
